<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + '智能设备'"
    width="1000px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>
<script>
import { add, detail, edit, pDeviceArr } from "@/api/iot/archives";
import { getnetworks } from "@/api/system/dept";
import { replaceDigit, replaceInteger } from "@/utils/index";
import { validDeviceCode } from "@/utils/validate";
import { typeAndLabelLv2Code } from "@/api/system/dict/data";
import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
export default {
  dicts: [
    "device_type",
    "device_model",
    "subentry_type",
    "device_functional_type",
    "device_sub_functional_type",
    "wmeter_device_model",
  ],
  components: {
    CascaderSelect,
    FormButton,
  },
  props: {
    id: { type: [Number, String], default: "" },
    visible: { type: Boolean, default: false },
    type: { type: Number, default: 0, require: false }, // 类型 0 电表 1水表
  },
  data() {
    return {
      live2Codes: [],
      loading: false,
      networkOptions: [],
      parentDeviceIdArr: [],
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 2,
              middle: true,
            },
            rules: {
              model: [
                {
                  required: true,
                  message: "请选择设备型号",
                  trigger: "change",
                },
              ],
              subentryType: [
                {
                  required: true,
                  message: "请选择分项类型",
                  trigger: "change",
                },
              ],
              type: [
                {
                  required: true,
                  message: "请选择设备类型",
                  trigger: "change",
                },
              ],
              functionalType: [
                {
                  required: true,
                  message: "请选择职能分类",
                  trigger: "change",
                },
              ],
              subFunctionalType: [
                {
                  required: true,
                  message: "请选择功能分类",
                  trigger: "change",
                },
              ],
              gatewayNo: [
                { required: true, message: "请填写网关号", trigger: "blur" },
              ],
              warrantyPeriod: [
                { required: true, message: "质保期限不能为空" },
                { type: "number", message: "质保期限必须为数字值" },
              ],
              ratedCurrent: [
                { required: true, message: "请填写额定电流", trigger: "blur" },
              ],
              caliber: [
                { required: true, message: "请填写口径", trigger: "blur" },
              ],
              cardNum: [
                {
                  required: true,
                  message: "请填写物联网卡号",
                  trigger: "blur",
                },
              ],
              ct: [{ required: true, message: "请填写CT", trigger: "blur" }],
              ratedPower: [
                { required: true, message: "请填写额定功率", trigger: "blur" },
              ],
              manufacturer: [
                { required: true, message: "请填写所属厂家", trigger: "blur" },
              ],
              code: [
                {
                  required: true,
                  message: "请输入设备编码",
                  trigger: "blur",
                },
                { validator: this.validCode },
              ],
              name: [
                { required: true, message: "请填写设备名称", trigger: "blur" },
              ],
              suggestChangeTime: [
                {
                  required: true,
                  message: "请选择建议更换日期",
                  trigger: "change",
                },
              ],
              installTime: [
                {
                  required: true,
                  message: "请选择安装时间",
                  trigger: "change",
                },
              ],
              installPerson: [
                { required: true, message: "请填写安装人员", trigger: "blur" },
              ],
              installLocation: [
                {
                  required: true,
                  message: "请填写安装物理位置",
                  trigger: "blur",
                },
              ],
              sysDeptId: [
                {
                  required: true,
                  message: "请选择所属用能单位",
                  trigger: ["blur", "change"],
                },
              ],
              monitoringNetworkId: [
                {
                  required: true,
                  message: "请选择所属检测终端",
                  trigger: ["blur", "change"],
                },
              ],
            },
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            type: {
              typeName: "el-select",
              label: "设备类型:",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.device_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().type;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("type", value);
                          that.$refs?.form?.setFieldValue("model", "");
                          if (value == 1) {
                            that.apsForm.formConfig.properties.caliber.display = false;
                            that.apsForm.formConfig.properties.cardNum.display = false;
                          } else {
                            that.apsForm.formConfig.properties.caliber.display = true;
                            that.apsForm.formConfig.properties.cardNum.display = true;
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            model: {
              typeName: "el-select",
              label: "设备型号:",
              render: (h) => {
                let that = this;
                let arr = [];

                if (that.$refs?.form?.getFieldsValue().type === 0) {
                  that.dict?.type?.device_model.some((item) => {
                    arr.push(item);
                  });
                } else if (that.$refs?.form?.getFieldsValue().type === 1) {
                  that.dict?.type?.wmeter_device_model.some((item) => {
                    arr.push(item);
                  });
                }
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().model;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: !(
                          that.$refs?.form?.getFieldsValue().type + 1
                        ),
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          if (
                            value == 2 &&
                            that.$refs?.form?.getFieldsValue().type === 0
                          ) {
                            that.apsForm.formConfig.properties.gatewayNo.display = false;
                          } else {
                            that.apsForm.formConfig.properties.gatewayNo.display = true;
                          }
                          that.$refs?.form?.setFieldValue("model", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            gatewayNo: {
              typeName: "el-input",
              label: "网关号",
              display: true,
            },
            caliber: {
              typeName: "el-input",
              label: "口径",
              display: true,
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入口径"
                      value={this.$refs?.form?.getFieldsValue().caliber}
                      clearable
                      onInput={(value) => this.keyFixAmount(value, "caliber")}
                    >
                      <template slot="append">mm</template>
                    </el-input>
                  </div>
                );
              },
            },
            cardNum: {
              typeName: "el-input",
              label: " 物联网卡号",
              display: true,
            },
            subentryType: {
              typeName: "el-select",
              label: "分项类型:",
              clearable: true,
              render: (h) => {
                let that = this;
                let arr = that.live2Codes;
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().subentryType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "subentryType",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { dictLabel, dictValue } = item;
                        return h("el-option", {
                          props: {
                            label: dictLabel,
                            value: Number(dictValue),
                            key: dictValue,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            functionalType: {
              typeName: "el-select",
              label: "职能分类:",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.device_functional_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().functionalType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "functionalType",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            subFunctionalType: {
              typeName: "el-select",
              label: "功能分类:",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.device_sub_functional_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().subFunctionalType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "subFunctionalType",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            sysDeptId: {
              typeName: "el-select",
              label: "所属用能单位",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      values={that.$refs?.form?.getFieldsValue().sysDeptId}
                      value={that.$refs?.form?.getFieldsValue().sysDeptId}
                      varient={"energy"}
                      onInput={that.getNetworkList}
                      clearable={false}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            monitoringNetworkId: {
              typeName: "el-select",
              label: "所属能耗终端",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().monitoringNetworkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: !that.$refs?.form?.getFieldsValue().sysDeptId,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "monitoringNetworkId",
                            value
                          );
                        },
                      },
                    },
                    [
                      that.networkOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            manufacturer: {
              typeName: "el-input",
              label: "所属厂家",
            },
            warrantyPeriod: {
              typeName: "el-input-number",
              label: "质保期限(年)",
            },
            qrCode: {
              typeName: "el-input",
              label: "二维码",
            },
            suggestChangeTime: {
              typeName: "el-date-picker",
              type: "date",
              label: "建议更换日期",
              "value-format": "yyyy-MM-dd",
              placeholder: "请选择建议更换日期",
            },
            code: {
              typeName: "el-input",
              label: "设备编码",
              placeholder: "请输入设备编码",
            },
            name: {
              typeName: "el-input",
              label: "设备名称",
            },
            parentDeviceId: {
              typeName: "el-select",
              label: "上级设备:",
              display: "",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [...that.parentDeviceIdArr];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parentDeviceId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: false,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "parentDeviceId",
                            value
                          );
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            ratedCurrent: {
              typeName: "el-input",
              label: "额定电流",
              display: true,
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入额定电流"
                      value={this.$refs?.form?.getFieldsValue().ratedCurrent}
                      clearable
                      onInput={(value) =>
                        this.keyFixAmount(value, "ratedCurrent")
                      }
                    >
                      <template slot="append">A</template>
                    </el-input>
                  </div>
                );
              },
            },
            ct: {
              typeName: "el-input",
              label: "电流变比CT",
              display: true,
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入CT"
                      value={this.$refs?.form?.getFieldsValue().ct}
                      clearable
                      onInput={(value) => this.keyFixAmount(value, "ct")}
                    ></el-input>
                  </div>
                );
              },
            },
            ratedPower: {
              typeName: "el-input",
              label: "额定功率",
              display: true,
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入额定功率"
                      value={this.$refs?.form?.getFieldsValue().ratedPower}
                      clearable
                      onInput={(value) =>
                        this.keyFixAmount(value, "ratedPower")
                      }
                    >
                      <template slot="append">W</template>
                    </el-input>
                  </div>
                );
              },
            },
            installTime: {
              typeName: "el-date-picker",
              type: "date",
              label: "安装时间",
              "value-format": "yyyy-MM-dd",
              placeholder: "请选择安装时间",
            },
            installPerson: {
              typeName: "el-input",
              label: "安装人员",
            },
            installLocation: {
              typeName: "el-input",
              label: "安装物理位置",
            },
            installationPicture: {
              typeName: "ImageUpload",
              limit: 2,
              fileSize: 5,
              accept: "image/*",
              // fileBigness: "311*140px",
              label: "安装现场图片",
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (this.type == 0) {
          this.getparentDeviceIdArr();
          this.apsForm.formConfig.properties.parentDeviceId.display = "";
        } else if (this.type == 1) {
          this.apsForm.formConfig.properties.parentDeviceId.display = "none";
        }
        this.getTypeAndLabelLv2Code();
        this.getNetwork();
        this.setClunm();
        if (String(this.id).length > 0) {
          setTimeout(() => {
            this.getInfo();
          }, 200);
        }
      }
    },
  },
  methods: {
    // 获取上级设备集合
    getparentDeviceIdArr() {
      this.parentDeviceIdArr = [];
      pDeviceArr({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.code ?? "",
                value: item?.id,
              };
              this.parentDeviceIdArr.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300027");
        });
    },
    getTypeAndLabelLv2Code() {
      let code = this.type === 0 ? 32 : this.type === 1 ? 33 : null;
      if (code) {
        typeAndLabelLv2Code("subentry_type", code).then((response) => {
          this.live2Codes = response.data;
        });
      }
    },
    validCode(rule, value, callback) {
      if (this.type === 1) {
        callback();
      } else {
        if (!validDeviceCode(value)) {
          callback("设备编码格式不正确");
        } else {
          callback();
        }
      }
    },
    getInfo() {
      detail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.ratedCurrent = newData.ratedCurrent / 100;
          newData.caliber = newData.deviceWaterEmeterVo?.caliber;
          newData.cardNum = newData.deviceWaterEmeterVo?.cardNum;
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300022");
        });
    },
    setClunm() {
      let that = this;
      setTimeout(() => {
        that.$refs?.form?.setFieldValue("type", this.type);
        that.$refs?.form?.setFieldValue("subFunctionalType", this.type);
        if (that.type == 1) {
          that.apsForm.formConfig.properties.caliber.display = false;
          that.apsForm.formConfig.properties.cardNum.display = false;
          that.apsForm.formConfig.properties.ratedPower.display = true;
          that.apsForm.formConfig.properties.ratedCurrent.display = true;
          that.apsForm.formConfig.properties.ct.display = true;
          that.apsForm.formConfig.properties.code.placeholder =
            "请输入设备编码";
        } else {
          that.apsForm.formConfig.properties.caliber.display = true;
          that.apsForm.formConfig.properties.cardNum.display = true;
          that.apsForm.formConfig.properties.ratedPower.display = false;
          that.apsForm.formConfig.properties.ratedCurrent.display = false;
          that.apsForm.formConfig.properties.ct.display = false;
          that.apsForm.formConfig.properties.code.placeholder =
            "请输入设备编码，例：(A-F 0-9)-(A-F 0-9)";
        }
      }, 500);
    },
    keyFixAmount(value, key) {
      if (key == "caliber" || key == "ratedPower") {
        this.$refs?.form?.setFieldValue(key, replaceInteger(value));
      } else {
        this.$refs?.form?.setFieldValue(key, replaceDigit(value, 2));
      }
    },
    getNetwork() {
      getnetworks({
        sysDeptId: this.$refs?.form?.getFieldsValue().sysDeptId,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.networkOptions = res.rows;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20001");
        });
    },
    getNetworkList(data) {
      let result;
      if (data && data.length > 0) {
        result = data[data.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("sysDeptId", result);
      this.$refs?.form?.setFieldValue("monitoringNetworkId", "");
      this.getNetwork();
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            ...this.$refs.form.getFieldsValue(),
            ratedCurrent: this.$refs.form.getFieldsValue().ratedCurrent * 100,
          };
          this.loading = true;
          if (this.id) {
            edit(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!300024");
              });
          } else {
            add(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!300023");
              });
          }
        } else {
          return false;
        }
      });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();

      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
}
</style>
